package com.ityj.yygh.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ityj.yygh.hospital.service.DepartmentService;
import com.ityj.yygh.hospital.repository.DepartmentRepository;
import com.ityj.yygh.model.hosp.Department;
import com.ityj.yygh.vo.hosp.DepartmentQueryVo;
import com.ityj.yygh.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public boolean save(Map<String, Object> stringObjectMap) {
        // data verify and transfer to Department
        if (stringObjectMap == null) {
            log.warn("Input parameter stringObjectMap is null!");
            return false;
        }
        String jsonString = JSONObject.toJSONString(stringObjectMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);

        // verify existence
        Department existDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        log.info("get 科室department-{}  from mongodb:{}", department.getHoscode(), existDepartment);
        if (existDepartment == null) {
            // not exist
            department.setIsDeleted(0);
            department.setCreateTime(new Date());
        } else {
            department.setIsDeleted(existDepartment.getIsDeleted());
            department.setCreateTime(existDepartment.getCreateTime());
        }
        department.setUpdateTime(new Date());
        departmentRepository.save(department);
        return true;
    }

    @Override
    public Page<Department> findDepartmentByCondition(DepartmentQueryVo departmentQueryVo, Integer pageNum, Integer pageSize) {
        // 创建Pageable对象，设置当前页及每页的大小
        // page – zero-based page index.
        Pageable pageable = PageRequest.of(pageNum - 1 , pageSize);
        //创建Example对象，用于放查询的条件
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        // 根据前端传过来的departmentQueryVo，构造一个Department对象
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        Example<Department> example = Example.of(department, matcher);
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public boolean remove(String hoscode, String depcode) {
        if (StringUtils.isAnyEmpty(hoscode, depcode)) {
            log.warn("Input param is incorrect!");
            return false;
        }

        // get department
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        // remove department
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }
        return true;
    }

    // 根据医院编码获取医院科室的详细信息
    @Override
    public List<DepartmentVo> findDepartmentDetailByHospcode(String hospcode) {
        Department department = new Department();
        department.setHoscode(hospcode);
        Example<Department> example = Example.of(department);
        List<Department> departmentList = departmentRepository.findAll(example);

        // 结构是List<Map<String, DepartmentVo>>  大科室下挂着小科室
        List<DepartmentVo> result = new ArrayList<>();

        // 现根据大科室分组，然后遍历组装最后结果
        Map<String, List<Department>> stringListMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        for (Map.Entry<String, List<Department>> entry : stringListMap.entrySet()) {
            // 大科室信息
            String bigcode = entry.getKey();
            List<Department> allChildDepartmentList = entry.getValue();
            // 当前大科室信息封装
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(bigcode);
            departmentVo.setDepname(allChildDepartmentList.get(0).getBigname());

            // 小科室信息封装
            List<DepartmentVo> childDepartmentVoList = new ArrayList<>();
            allChildDepartmentList.forEach(childDepartment -> {
                DepartmentVo childDepartmentVo = new DepartmentVo();
                childDepartmentVo.setDepcode(childDepartment.getDepcode());
                childDepartmentVo.setDepname(childDepartment.getDepname());
                childDepartmentVoList.add(childDepartmentVo);
            });
            departmentVo.setChildren(childDepartmentVoList);
            result.add(departmentVo);
        }
        return result;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (department != null) {
            return department.getDepname();
        }
        return "";
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
